package com.aliyun;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.green.model.v20180509.ImageSyncScanRequest;
import com.aliyuncs.http.FormatType;
import com.aliyuncs.http.HttpResponse;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.motu.vertx.module.utility.base.BaseServerParam;
import com.motu.vertx.module.utility.toolset.Tool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;

/**
 * 阿里云图片检测接口
 */
public class ImageSyncScan extends BaseSample {

    private static final Logger logger = LoggerFactory.getLogger(ImageSyncScan.class);

    /**
     * 图片检测（地区不同）
     */
    public static boolean check(String url, String regionId) {
        BaseSample.regionId = regionId;
        return check(url);
    }

    /**
     * 图片检测（密钥不同）
     */
    public static boolean check(String url, String accessKeyId, String accessKeySecret) {
        BaseSample.accessKeyId = accessKeyId;
        BaseSample.accessKeySecret = accessKeySecret;
        return check(url);
    }

    /**
     * 图片检测（地区和密钥都不同）
     */
    public static boolean check(String url, String regionId, String accessKeyId, String accessKeySecret) {
        BaseSample.regionId = regionId;
        BaseSample.accessKeyId = accessKeyId;
        BaseSample.accessKeySecret = accessKeySecret;
        return check(url);
    }

    /**
     * 图片检测（使用BaseSample默认配置信息）
     */
    public static boolean check(String url) {
        try {
            // 不开启自动审核就表示审核通过
            if (BaseServerParam.AUTO_CHECK_IMAGE == 0){
                return true;
            }
            //请替换成你自己的accessKeyId、accessKeySecret
            IClientProfile profile = DefaultProfile.getProfile(regionId, accessKeyId, accessKeySecret);
            DefaultProfile.addEndpoint(getEndPointName(), regionId, "Green", getDomain());
            IAcsClient client = new DefaultAcsClient(profile);

            ImageSyncScanRequest imageSyncScanRequest = new ImageSyncScanRequest();
            imageSyncScanRequest.setAcceptFormat(FormatType.JSON); // 指定api返回格式
            imageSyncScanRequest.setMethod(com.aliyuncs.http.MethodType.POST); // 指定请求方法
            imageSyncScanRequest.setEncoding("utf-8");
            imageSyncScanRequest.setRegionId(regionId);


            List<Map<String, Object>> tasks = new ArrayList<Map<String, Object>>();
            Map<String, Object> task = new LinkedHashMap<String, Object>();
            task.put("dataId", UUID.randomUUID().toString());
            task.put("url", url);
            task.put("time", new Date());

            tasks.add(task);
            JSONObject data = new JSONObject();
            /**
             * porn: 色情
             * terrorism: 暴恐
             * qrcode: 二维码
             * ad: 图片广告
             * ocr: 文字识别
             */
            data.put("scenes", Arrays.asList("porn", "terrorism", "ad"));
            data.put("tasks", tasks);

            imageSyncScanRequest.setHttpContent(data.toJSONString().getBytes("UTF-8"), "UTF-8", FormatType.JSON);

            /**
             * 请务必设置超时时间
             */
            imageSyncScanRequest.setConnectTimeout(3000);
            imageSyncScanRequest.setReadTimeout(10000);


            HttpResponse httpResponse = client.doAction(imageSyncScanRequest);

            if (httpResponse.isSuccess()) {
                JSONObject scrResponse = JSON.parseObject(new String(httpResponse.getHttpContent(), "UTF-8"));
                logger.info(JSON.toJSONString(scrResponse, true));
                if (200 == scrResponse.getInteger("code")) {
                    JSONArray taskResults = scrResponse.getJSONArray("data");
                    for (Object taskResult : taskResults) {
                        if (200 == ((JSONObject) taskResult).getInteger("code")) {
                            JSONArray sceneResults = ((JSONObject) taskResult).getJSONArray("results");
                            for (Object sceneResult : sceneResults) {
                                String scene = ((JSONObject) sceneResult).getString("scene");
                                String suggestion = ((JSONObject) sceneResult).getString("suggestion");
                                //根据scene和suggetion做相关的处理
                                //do something
//                                System.out.println("args = [" + scene + "]");
//                                System.out.println("args = [" + suggestion + "]");
                                /**
                                 * suggestion取值
                                 * pass：图片正常，无需进行其余操作；或者未识别出目标对象
                                 * review：检测结果不确定，需要进行人工审核；或者识别出目标对象
                                 * block：图片违规，建议执行进一步操作（如直接删除或做限制处理）
                                 */
                                //审核严格
                                if (!suggestion.equalsIgnoreCase("pass")) {
                                    return false;
                                }
                                //审核宽松
//                                if (suggestion.equalsIgnoreCase("block")) {
//                                    return false;
//                                }
                            }
                        } else {
                            logger.error("task process fail:" + ((JSONObject) taskResult).getInteger("code"));
                            return false;
                        }
                    }
                } else {
                    logger.error("detect not success. code:" + scrResponse.getInteger("code"));
                    return false;
                }
            } else {
                logger.error("response not success. status:" + httpResponse.getStatus());
                return false;
            }
        } catch (ServerException e) {
            logger.error(Tool.getException(e));
            return false;
        } catch (ClientException e) {
            logger.error(Tool.getException(e));
            return false;
        } catch (Exception e) {
            logger.error(Tool.getException(e));
            return false;
        }
        return true;
    }

}
